package com.hooper.login.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hooper.login.entity.CityInfo;
import com.hooper.login.entity.Region;
import com.hooper.login.entity.vo.RegionVo;
import com.hooper.login.mapper.CityInfoMapper;
import com.hooper.login.mapper.RegionMapper;
import com.hooper.login.service.RegionService;
import com.hooper.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mind
 * @description 针对表【region】的数据库操作Service实现
 * @createDate 2023-01-31 14:46:57
 */
@Service
public class RegionServiceImpl extends ServiceImpl<RegionMapper, Region>
        implements RegionService {
    @Resource
    private CityInfoMapper cityInfoMapper;


    @Override
    public void saveRegion(String regionName, List<String> cityNames) {
        if (StringUtils.isBlank(regionName)) {
            throw new RuntimeException("para empty!");
        }
        LambdaQueryWrapper<CityInfo> wrapper = new LambdaQueryWrapper<>();

        wrapper.in(CityInfo::getName, cityNames);

        List<CityInfo> cityInfoList = cityInfoMapper.selectList(wrapper);
        List<Long> idList = cityInfoList.stream().map(CityInfo::getId).collect(Collectors.toList());
        String cityIds = JSONUtil.toJsonStr(idList);
        Region region = new Region();
        region.setRegionName(regionName);
        region.setCityId(cityIds);
        baseMapper.insert(region);
    }

    @Override
    public List<RegionVo> getRegionList() {
        List<Region> regionList = baseMapper.selectList(null);
        return regionList.stream().map(region -> {
            String json = region.getCityId();
            List<Long> cityIds = JSONUtil.toList(json, Long.class);
            List<String> cityInfos = cityInfoMapper.selectBatchIds(cityIds)
                    .stream().map(CityInfo::getName).collect(Collectors.toList());
            RegionVo regionVo = new RegionVo();
            regionVo.setRegionName(region.getRegionName());
            regionVo.setCreateTime(RandomUtil.randomStrDate(2022));
            regionVo.setCityInfos(cityInfos);
            LambdaQueryWrapper<CityInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CityInfo::getParentId, cityIds);
            List<String> addrInfo = cityInfoMapper.selectList(wrapper)
                    .stream().map(CityInfo::getName).collect(Collectors.toList());
            regionVo.setAddrInfo(addrInfo);
            return regionVo;
        }).collect(Collectors.toList());
    }
}




